import {
	defineStore
} from 'pinia';
import {
	request
} from '@/utils/api';
import {
	requestPermissionall,
	requestPermission
} from '@/js_sdk/nh-authorize/nh-authorize.js'
export const mainStore = defineStore('mainStore', {
	state: () => {
		return {
			userInfo: {
				"nickName": "",
				"userName":"",
				"avatar": "",
				
				"gender": 0,
				"language": "",
				"city": "",
				"province": "",
				"country": "",
				"is_demote": true,
				userPhone: {
					encryptedData: '',
					iv: ''
				}
			},
			token: '',
			version: '1.1.9'
		};
	},

	actions: {
		async getUserInfo() {
			try{
				let _this = this
				let res = await request({
					url: '/sanitation/v1/me',
					method: 'GET'
				})
				_this.setUserInfo(res)
			}
			catch(e){
				
			}

		},
		async updateUserInfo(userInfo){
			try{
				let _this = this
				let res = await request({
					url: '/sanitation/v1/me',
					method: 'put',
					data:userInfo
				})
				await _this.setUserInfo(userInfo)
			}
			catch(e){
				
			}
			
		},
		async setUserInfo(userInfo) {
			this.userInfo = {
				...this.userInfo,
				...userInfo
			}
			await uni.setStorageSync('userInfo', this.userInfo)
		},
		login() {
			return new Promise((resolve, reject) => {
				uni.login({
					provider: 'weixin',
					success: (loginRes) => {
						const {
							code
						} = loginRes;
						// 发送code到后台换取openId, sessionKey, unionId
						console.log(loginRes)
						resolve(code)
					},
					fail: (err) => {
						console.log('uni.login 接口调用失败，将无法正常使用开放接口等服务', err);
						uni.showToast({
							title: '登录失败',
							icon: 'none'
						});
						reject('uni.login 接口调用失败，将无法正常使用开放接口等服务')
					}
				});
			})

		},
		loginOut() {
			this.userInfo = {
				"nickName": "",
				"gender": 0,
				"language": "",
				"city": "",
				"province": "",
				"country": "",
				"avatarUrl": "",
				"is_demote": true,
				userPhone: {
					encryptedData: '',
					iv: ''
				}
			}
			this.token = ''
			uni.setStorageSync('token', '')
			request({
				url: '/sanitation/v1/logout',
				method: 'POST'
			}).then(res => {
				console.log("退出成功")
			})
		}
	},
});